#include <queue>
#include <vector>
using namespace std;

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
// 思路： 使用队列进行层序遍历
//  问题：我怎么确定每一层的节点个数呢？ 每一次进入while循环时，队列中的节点个数就是当前层的节点个数
class Solution
{
public:
    vector<vector<int>> levelOrder(TreeNode *root)
    {
        queue<TreeNode *> q;
        vector<vector<int>> res;
        if (!root)
            return res;
        q.push(root);
        while (!q.empty())
        {
            int q_len = q.size(); // 当前层的节点个数
            vector<int> temp;
            for (int i = 0; i < q_len; ++i)
            {
                TreeNode *node = q.front();
                q.pop();
                temp.push_back(node->val);
                if (node->left)
                    q.push(node->left);
                if (node->right)
                    q.push(node->right);
            }
            if (q_len)
                res.push_back(temp);
        }
        return res;
    }
};